/*************************************************************************
	> File Name: testmap.cpp
	> Author: 
	> Mail: 
	> Created Time: 2017年06月01日 星期四 17时31分30秒
 ************************************************************************/

#include <pthread.h>
#include <stddef.h>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <utility>

//#include <iostream>
using namespace std;
#include "cuckoohash_map.hh"


struct KeyNow
{
	char *keyStr;
//	int keyNum;
	KeyNow &operator =(const KeyNow& term)
	{
		keyStr = term.keyStr;
		return *this;
	}
	KeyNow(char* Str)
	{
		this->keyStr = Str;
		//keyNum = num;
	}

};

struct hash_func  //hash 函数
{

    size_t operator()(const KeyNow &addr) const
    {
    	char *str = addr.keyStr;
    	int len = strlen(str);

//    	size_t hash = 0;
//
//    	for(int i = 0; i < len; str++, i++)
//    	{
//    		hash = (*str) + (hash << 6) + (hash << 16) - hash;
//    	}
//
//    	return hash;

		size_t h = 0;
		for( const char* s = str; *s; ++s )
			h = (h*17)^*s;
		return h;

    	//return addr.keyNum * 88;
    }
};
struct cmp_fun //比较函数 ==
{
    bool operator()(const KeyNow &addr1, const KeyNow &addr2) const
    {
    	return strcmp(addr1.keyStr,addr2.keyStr) == 0;
         //return addr1.keyNum == addr2.keyNum;
    }
};

//typedef cuckoohash_map<KeyNow, string,hash_func,cmp_fun> HashJuz;
typedef cuckoohash_map<KeyNow, string,hash_func,cmp_fun> HashJuz;
//typedef cuckoohash_map<int*, string> HashJuz;
HashJuz Table;

void* thread3( void *arg )
{

	string test;
	while(1)
	{
		for(int i = 0 ; i < 100; i++)
		{
			cout<<"上锁"<<endl;
		}
		auto  lt = Table.lock_table();
	    for (const auto &it : lt) {
	    	KeyNow kn = it.first;
	    	test = it.second;
	    	cout<<"自定义key:"<<kn.keyStr<<":"<<test.c_str()<<endl;
	    }
	    cout<<"休息５秒!"<<endl;
	    lt.unlock();
	    sleep(5);
	}

}
void* thread2( void *arg )
{
	for(int i = 0 ; i < 80000000;i++)
	{
		char *pp = new char[64];
		sprintf(pp,"%d",i);
		KeyNow kn(pp);
		//int *test1 = new int;
		//*test1 = i;
		if(Table.erase(kn))
		{
			//cout<<"删除成功! "<<pp<<endl;
		}
		else
		{
		//	cout<<"删除失败! "<<pp<<endl;
		}
	//	cout<<"删除:"<<i<<endl;
	}
}
void* thread1( void *arg )
{
	for(int i = 0 ; i < 80000000;i++)
	{
		char *pp = new char[64];
		sprintf(pp,"%d",i);
		KeyNow kn(pp);
		//int *pNum = new int;
	//	*pNum = i;

		Table.insert(kn,"hello");
		//cout<<"插入:"<<i<<endl;
	}
}

int main()
{
    pthread_t th1,th2,th3;

   pthread_create( &th1, NULL, thread1, NULL);
   sleep(1);
   pthread_create( &th2, NULL, thread2, NULL);
   sleep(1);
   pthread_create( &th3, NULL, thread3, NULL);

   sleep(300);
	return 0;
}
